package cn.zyl.inwatchappphoneside;

import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.file.zip.ZipEntry;
import com.file.zip.ZipFile;
import com.tencent.tws.api.FileTransferManager;
import com.tencent.tws.api.PassThroughDataResultInfo;
import com.tencent.tws.api.PassThroughManager;

import org.ini4j.Wini;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class WatchFaceListActivity extends AppCompatActivity {

    private GridView gridView;
    private TextView textViewMSG;
    private ArrayList<HashMap<String, Object>> watchFaces = new ArrayList<>();   //grid九宫格数据
    private FileTransferManager fileTransferManager;
    private PassThroughManager passThroughManager;
    private List<String> checkSend = new ArrayList<>();
    private int cPos = -1;  //当前选中安装的表盘
    private String cText = "";  //当前选中的表盘的名字
    private String pText = "";  //...
    private String cName = "";  //手表端当前选中的表盘
    private Timer timer;
    private SimpleAdapter simpleAdapter;
    private String sdCard = "";

    Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case 1001:
                    //正在安装
                    if (pText.equals("..."))
                        pText = "";
                    pText = pText+".";
                    watchFaces.get(cPos).put("text",cText+pText);
                    simpleAdapter.notifyDataSetChanged();
                    return true;
                case 1002:
                    //安装完成
                    cName = cText;
                    watchFaces.get(cPos).put("text",cText);
                    simpleAdapter.notifyDataSetChanged();
                    cText = "";
                    pText = "";
                    return true;
                case 1003:
                    //设置当前选中的表盘
                    simpleAdapter.notifyDataSetChanged();
                    return true;
            }
            return false;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_watch_face_list);
        gridView = (GridView)findViewById(R.id.gridView);
        textViewMSG = (TextView)findViewById(R.id.noGrid);
        fileTransferManager = FileTransferManager.getInstance(WatchFaceListActivity.this);
        passThroughManager = PassThroughManager.getInstance(WatchFaceListActivity.this);
        //这里检查一下是不是第一次使用(用本地存储)
        String version = "20160805.1";
        SharedPreferences sp = this.getSharedPreferences("ZYL", MODE_PRIVATE);
        if (!sp.getString("version","").equals(version)){
            unZipWatchFace(); //解压内置的表盘吧
//            if (check){
                //再写入版本号(不管有没有成功都写一下吧，有些没有写外置sd卡的权限)
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("version",version);
                editor.apply();
//            }
        }
        initWatchFaces();
        initWatchSide();
        simpleAdapter = new SimpleAdapter(this,watchFaces,R.layout.activity_watch_face_list_items,
                new String[]{"text","image"},
                new int[]{R.id.textView1,R.id.imageView1});
        simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
            @Override
            public boolean setViewValue(View view, Object data, String textRepresentation) {
                if (view instanceof ImageView){
                    ImageView imageView = (ImageView) view;
                    if (!data.equals("")){
                        imageView.setImageBitmap(BitmapFactory.decodeFile((String)data));
                    }
                    return true;
                }else if(view instanceof TextView){
                    TextView textView = (TextView)view;
                    if (textView.getText().equals(cName)){
                        textView.setTextColor(Color.BLUE);
                    }else{
                        textView.setTextColor(Color.BLACK);
                    }
                }
                return false;
            }
        });
        gridView.setAdapter(simpleAdapter);
        //点击事件
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (checkSend.size()>0){
                    Toast.makeText(getApplicationContext(),"表盘正在安装中...请稍候",Toast.LENGTH_LONG).show();
                    return;
                }
                cPos = position;
                //准备安装并切换
                JSONObject json = new JSONObject();
                try {
                    json.put("cmd","changeWatchFace");   //切换表盘命令
                    json.put("dir",watchFaces.get(position).get("text"));   //文件夹名称
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                passThroughManager.sendData(json.toString(), "com.example.zyl.inwatchapp", new PassThroughManager.PassThroughSendDataResultListener() {
                    @Override
                    public void onReceiveSendDataResult(int i) {
                        if (i!= PassThroughDataResultInfo.SUC){
                            //消息发送失败
                            Toast.makeText(getApplicationContext(),i+":与InwatchT通讯失败，请先运行一次手表端app,或者检查腾讯手表助手有没有运行。",Toast.LENGTH_LONG).show();
                        }
                    }
                });
            }
        });
        //长按删除
        gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(WatchFaceListActivity.this);
                final String dir = watchFaces.get(position).get("text").toString();  //当前表盘
                if (cName.equals(dir)){
                    builder.setMessage("正在使用的表盘不能删除！");
                    builder.setPositiveButton("确定",null);
                    builder.show();
                    return true;
                }
                builder.setMessage("确定要删除手表端表盘["+dir+"]？\r\n（注：手机端请手动删除“手机存储卡/zylWatchFace”下的表盘）");
                builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        JSONObject json = new JSONObject();
                        try {
                            json.put("cmd","delWatchFace");   //删除表盘命令
                            json.put("dir",dir);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        passThroughManager.sendData(json.toString(), "com.example.zyl.inwatchapp",null);
                    }
                });
                builder.setNegativeButton("取消", null);
                builder.show();
                return true;
            }
        });
    }

    /**
     * 删除目录
     * @param file
     */
    private void DeleteFile(File file) {
        if (file.exists() == false) {
            return;
        } else {
            if (file.isFile()) {
                file.delete();
                return;
            }
            if (file.isDirectory()) {
                File[] childFile = file.listFiles();
                if (childFile == null || childFile.length == 0) {
                    file.delete();
                    return;
                }
                for (File f : childFile) {
                    DeleteFile(f);
                }
                file.delete();
            }
        }
    }

    /**
     * 复制assets中的表盘资源到sdcard
     */
    private boolean unZipWatchFace(){
        try{
            sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(sdCard+"/zylWatchFace/");
            if (file.exists()){
                //如果已经存在，就删除默认的那4个表盘，不删用户自己添加的表盘
                DeleteFile(new File(file.getAbsoluteFile()+"/ticwatch"));
                DeleteFile(new File(file.getAbsoluteFile()+"/多功能"));
                DeleteFile(new File(file.getAbsoluteFile()+"/蓝欧米茄"));
                DeleteFile(new File(file.getAbsoluteFile()+"/数字电波"));
                DeleteFile(new File(file.getAbsoluteFile()+"/议员大日历"));
            }
//            if (!file.exists()) {
                //给其它安装表盘的话，我考虑再重新写一个吧
                AssetManager assetManager = getAssets();
                String[] files = assetManager.list("");
                for (String file1:files){
                    if (file1.equals("zylWatchFace.zip")){
                        //先从assets复制到sdcard，之后再进行解压吧
                        copyBigDataToSD("zylWatchFace.zip",sdCard+"/zylWatchFace.zip");
                        File dir = new File(sdCard+"/zylWatchFace/");
                        if (!dir.exists())
                            dir.mkdir();
                        File zipfile = new File(sdCard+"/zylWatchFace.zip");
                        unzip(zipfile,sdCard+"/zylWatchFace/");  //解压
                        //mtp的扫描还有问题，算了。
//                        Uri uri = Uri.parse(dir.toString());
//                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,uri));
//                        MediaScannerConnection.scanFile(this, new String[]{dir.toString()}, null, new MediaScannerConnection.OnScanCompletedListener() {
//                            @Override
//                            public void onScanCompleted(String path, Uri uri) {
//                                Log.i("zyltest",path);
//                                Log.i("zyltest",uri.getPath());
//                            }
//                        });
                    }
                }
//            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            String msg = "默认表盘文件安装失败，请手动复制[zylWatchFace]目录到["+sdCard+"/]目录下面！！！\r\n" +
                    "如果是android6.0及以上系统请赋予本软件的存储盘读写权限...";
            textViewMSG.setText(msg);
        }
        return false;
    }

    private void copyBigDataToSD(String assetsFileName,String strOutFileName) throws IOException
    {
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(strOutFileName);
        myInput = this.getAssets().open(assetsFileName);
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while(length > 0)
        {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }

        myOutput.flush();
        myInput.close();
        myOutput.close();
    }

    /**
     * @param file      待解压文件
     * @param dir       解压后文件的存放目录
     * @throws IOException
     */
    public void unzip(File file, String dir) throws IOException {
        ZipFile zipFile = new ZipFile(file, "GBK");//设置压缩文件的编码方式为GBK
        Enumeration<ZipEntry> entris = zipFile.getEntries();
        ZipEntry zipEntry = null;
        File tmpFile = null;
        BufferedOutputStream bos = null;
        InputStream is = null;
        byte[] buf = new byte[1024];
        int len = 0;
        while (entris.hasMoreElements()) {
            zipEntry = entris.nextElement();
            // 不进行文件夹的处理,些为特殊处理
            tmpFile = new File(dir + zipEntry.getName());
            if (zipEntry.isDirectory()) {//当前文件为目录
                if (!tmpFile.exists()) {
                    tmpFile.mkdir();
                }
            } else {
                if (!tmpFile.exists()) {
                    tmpFile.createNewFile();
                }
                is = zipFile.getInputStream(zipEntry);
                bos = new BufferedOutputStream(new FileOutputStream(tmpFile));
                while ((len = is.read(buf)) > 0) {
                    bos.write(buf, 0, len);
                }
                bos.flush();
                bos.close();
            }
        }
    }

    /**
     * 初始化手表端消息接收
     */
    private void initWatchSide(){
        //这里读取一下手表端当前选中的表盘
        JSONObject json = new JSONObject();
        try {
            json.put("cmd","currentWatchFace");   //当前表盘命令
        } catch (JSONException e) {
            e.printStackTrace();
        }
        passThroughManager.sendData(json.toString(), "com.example.zyl.inwatchapp",null);
        //准备安装并切换
        passThroughManager.regDataRecver(new PassThroughManager.PassThroughReceiveDataListener() {
            @Override
            public void onReceivePassThroughResult(int resultCode, String data) {
                if (resultCode == PassThroughDataResultInfo.SUC){
                    try{
                        final JSONObject json = new JSONObject(data);
                        if (json.optString("cmd").equals("currentWatchFace")){
                            cName = json.optString("dir","");
                            WatchFaceListActivity.this.handler.sendEmptyMessage(1003);
                        }else if (json.optString("cmd").equals("changeWatchFace")){
                            if (json.optBoolean("success",false)){
                                cName = json.optString("dir","");
                                WatchFaceListActivity.this.handler.sendEmptyMessage(1003);
                                //如果切换成功
                                Toast.makeText(getBaseContext(), "表盘["+json.optString("dir")+"]切换成功。" , Toast.LENGTH_LONG).show();
                            }else{
                                Toast.makeText(getBaseContext(), "表盘["+json.optString("dir")+"]开始安装..." , Toast.LENGTH_LONG).show();
                                //如果需要上传表盘
                                cText = watchFaces.get(cPos).get("text").toString();
                                timer = new Timer();
                                timer.schedule(new TimerTask() {
                                    @Override
                                    public void run() {
                                        WatchFaceListActivity.this.handler.sendEmptyMessage(1001);
                                    }
                                },0,1000);
                                checkSend.clear();
//                                String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
                                File file = new File(sdCard+"/zylWatchFace/"+json.optString("dir"));
                                sendFileToWatch(json,file);
                            }
                        }else if(json.optString("cmd").equals("delWatchFace")){
                            if (json.optBoolean("success",false)){
                                //如果删除成功
                                Toast.makeText(getBaseContext(), "表盘["+json.optString("dir")+"]删除成功。" , Toast.LENGTH_LONG).show();
                            }else{
                                Toast.makeText(getBaseContext(), "表盘["+json.optString("dir")+"]删除失败。" , Toast.LENGTH_LONG).show();
                            }
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }else{
                    Toast.makeText(getBaseContext(), "手机端接收数据失败，错误代码：" + resultCode, Toast.LENGTH_LONG).show();
                }
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_watch_face_menus,menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId()==R.id.menu_refresh){
            initWatchFaces();
            //这里刷新一下adapter吧
            simpleAdapter.notifyDataSetChanged();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * 发送文件到手表端
     */
    private void sendFileToWatch(final JSONObject json,File file){
        File[] files = file.listFiles();
        for (File file1:files){
            if (file1.isDirectory()){
                sendFileToWatch(json,file1);
            }else{
//                String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
                String dstPath = file1.getAbsolutePath().substring(sdCard.length(),file1.getAbsolutePath().lastIndexOf("/"));
                checkSend.add(file1.getAbsolutePath());
                Log.d("zyltest","src:"+file1.getAbsolutePath());
                Log.d("zyltest","dst:"+dstPath);
                //这里要循环上传了
                fileTransferManager.sendFile(file1.getAbsolutePath(), dstPath, new FileTransferManager.FileTransferListener() {
                    @Override
                    public void onTransferError(long requestId, String fileName, int errorCode) {
                        Log.d("zyltest","progress:"+requestId+"||"+fileName+"||"+errorCode);
                        checkSend.clear();
                        timer.cancel();
                        WatchFaceListActivity.this.handler.sendEmptyMessage(1002);
                        Toast.makeText(getBaseContext(), "表盘["+json.optString("dir")+"]安装失败，error："+errorCode , Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onTransferComplete(long requestId, String filePath) {
                        Log.d("zyltest","complete:"+filePath);
                        checkSend.remove(filePath);
                        if (checkSend.size()==0){
                            timer.cancel();
                            WatchFaceListActivity.this.handler.sendEmptyMessage(1002);
                            Toast.makeText(getBaseContext(), "表盘["+json.optString("dir")+"]安装并切换成功。" , Toast.LENGTH_LONG).show();
                            //最后再通知一下手表上传成功了
                            passThroughManager.sendData(json.toString(), "com.example.zyl.inwatchapp", new PassThroughManager.PassThroughSendDataResultListener() {
                                @Override
                                public void onReceiveSendDataResult(int i) {
                                    if (i!= PassThroughDataResultInfo.SUC){
                                        //消息发送失败
                                        Toast.makeText(getApplicationContext(),i+":与InwatchT通讯失败，请先运行一次手表端app,或者检查腾讯手表助手有没有运行。",Toast.LENGTH_LONG).show();
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onTransferCancel(long requestId, int reason) {
                        Log.d("zyltest","cancel:"+requestId+"||"+reason);
                        checkSend.clear();
                        timer.cancel();
                        WatchFaceListActivity.this.handler.sendEmptyMessage(1002);
                        Toast.makeText(getBaseContext(), "表盘["+json.optString("dir")+"]安装失败，cancel："+reason , Toast.LENGTH_LONG).show();
                    }

                    @Override
                    public void onTransferProgress(long requestId, String fileName, long progress) {
                        Log.d("zyltest","progress:"+requestId+"||"+fileName+"||"+progress);
//                        Toast.makeText(getBaseContext(), "正在传输文件("+progress+"%)："+fileName , Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }
    }

    /**
     * 读取sdcard表盘
     */
    private void initWatchFaces(){
        //读取sdcard的表盘资源
        try{
            watchFaces.clear();  //先清空，再重新读取一下
            String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
            File file = new File(sdCard+"/zylWatchFace");
            if (file.exists()) {
                File[] files = file.listFiles();
                for (File file1:files){
                    if(file1.isDirectory()){  //如果是文件夹
                        HashMap<String,Object> item = new HashMap<>();
                        item.put("text",file1.getName());
                        File file_config = new File(file1.getAbsolutePath()+"/config.ini");
                        Wini wini = new Wini(file_config);
                        String pic = wini.get("config","Preview");  //读取预览图片
                        if (pic==null||!(new File(file1.getAbsolutePath()+"/"+pic).exists())){
                            item.put("image","");   //没有预览图片就读取图标吧
                        }else{
                            item.put("image",file1.getAbsolutePath()+"/"+pic);
                        }
                        watchFaces.add(item);
                    }
                }
            }
            if (watchFaces.size()==0){
                textViewMSG.setVisibility(View.VISIBLE);
            }else{
                textViewMSG.setVisibility(View.GONE);
            }
        }catch(Exception e){
            Toast.makeText(this,e.getMessage()+"||"+e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }
}
